import { isPlainObject } from 'lodash-es';
import { i18n } from '../locale';

export const DEFAULT_TABNAVS = {
  index: { to: { name: 'home' }, icon: 'hospitalize-vip', text: i18n.tv('tabbar.home', '就医绿通'), target: '_self' },
  'user-center': { to: { name: 'mine' }, icon: 'tabbar-mine', text: i18n.tv('tabbar.my', '个人中心'), target: '_self' },
};

function mergeEntry(items, defaultItems) {
  const defaultTabnavKeys = Object.keys(defaultItems);
  return items.reduce((prev, nav) => {
    if (Array.isArray(nav) && nav.length >= 1) {
      // ['index'] 从默认配置中读取
      if (nav.length === 1) {
        if (defaultTabnavKeys.includes(nav[0])) {
          const key = nav[0];
          prev[key] = defaultItems[key];
        }
      } else if (isPlainObject(nav[1])) {
        // ['index',{to:'/custom/to'}] 合并配置
        const key = nav[0];
        const customConfig = nav[1];

        // 合并
        const config = Object.assign({}, { icon: 'self-exam', target: '_self' }, defaultItems[key], customConfig);
        // 必须要有 text / to
        // if (config.text && config.to) {
        if (config.text) {
          prev[key] = config;
        }
        return prev;
      } else {
        return prev;
      }
    }
    return prev;
  }, {});
}

export function formatConfig(config = {}) {
  const { colors = [], profile = {}, ...configRest } = config;
  // FIXME: 绿通不能走一体化配置
  // const { setting: settingStr = '{}' } = profile;
  // const setting = JSON.parse(settingStr);
  const setting ={}
  const { tabNavs = [], homeTips, homeAgreementConfirm, ...settingRest } = setting;
  return {
    primary: colors[0],
    colors,
    setting,
    profile,
    tabNavs: tabNavs.length ? mergeEntry(tabNavs, DEFAULT_TABNAVS) : DEFAULT_TABNAVS,
    homeTips:
      homeTips &&
      Object.assign(
        { text: 'Tips', leftIcon: 'volume-o' },
        typeof homeTips === 'string' ? { text: homeTips } : homeTips,
      ),
    homeAgreementConfirm:
      homeAgreementConfirm &&
      Object.assign({ title: '提示', message: 'Tips', confirmButtonEnableDalay: 0 }, homeAgreementConfirm),
    ...configRest,
    ...settingRest,
  };
}
